package com.itheima.tliaswebmanagement.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.tliaswebmanagement.anno.RecordOperationLog;
import com.itheima.tliaswebmanagement.pojo.Result;
import com.itheima.tliaswebmanagement.utils.AliOSSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 接收文件数据并响应
 */
@RestController
@RequestMapping("/upload")
public class UploadController {
    private final AliOSSUtils aliOSSUtils;

    @Autowired
    public UploadController(AliOSSUtils aliOSSUtils) {
        this.aliOSSUtils = aliOSSUtils;
    }

    /**
     * 服务端接收到前端上传的图片后,必须在图片被销毁前保存图片至本地或云端,并将图片访问路径反馈给前端,前端便能显示图片<br>
     * 响应参数为URL格式
     *
     * @param image MultipartFile对象
     * @return 文件访问路径（URL）
     * @throws IOException     IOException
     * @throws ClientException ClientException
     */
    @PostMapping
    @RecordOperationLog
    public Result upload(MultipartFile image) throws IOException, ClientException {
        System.out.println("文件上传...");
        // 保存图片至云端,并获得访问路径
        String url = aliOSSUtils.upload(image);
        return Result.success(url);
    }
}
